<template>
    <div class="mpub-content">
        <div class="tip">
            <div class="tip-bck">
                <img class="tip-bck-icon" src="@/assets/imgs/tip.png" />
                <span>最新版本 {{ newMiniapp.version }}</span>
            </div>
            <div class="tip-bck">
                <span>发布时间： </span>
                <span>{{ newMiniapp.createTime }}</span>
            </div>
        </div>
        <div class="zw-form-layout">
            <el-form ref="formRef" :model="form" label-width="auto">
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="小程序名称/APPID" prop="appid">
                            <el-input
                                maxlength="20"
                                v-model.trim="form.appid"
                                placeholder="请输入小程序名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="当前版本" prop="onlineVersion">
                            <el-input
                                maxlength="20"
                                v-model.trim="form.onlineVersion"
                                placeholder="请输入当前版本"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="发布时间" prop="date">
                            <el-date-picker
                                v-model="form.date"
                                type="daterange"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                :default-time="defaultDateRange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="提审版本审核状态" prop="status">
                            <el-select v-model="form.status" placeholder="请选择状态" clearable>
                                <el-option
                                    v-for="item in statusList"
                                    :key="item.key"
                                    :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="16" class="zw-form-btns">
                        <el-button type="primary" @click="searchHandler">查询</el-button>
                        <el-button plain @click="resetHandler">清空</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <el-row>
            <el-col class="zw-table-btns flex-left">
                <el-button type="primary" @click="batchPushHandler" :disabled="multipleSelection.length === 0">
                    批量发布
                </el-button>
                <el-button type="primary" plain @click="batchRevertHandler" :disabled="multipleSelection.length === 0">
                    批量回滚
                </el-button>
            </el-col>
        </el-row>
        <el-table :data="tableList" :border="true" stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="小程序">
                <template v-slot="{ row }">
                    <div class="dfl">
                        <span>{{ row.name }}</span>
                        <span>{{ row.appid }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="商户">
                <template v-slot="{ row }">
                    <div class="dfl">
                        <span>{{ row.shopName }}</span>
                        <span>{{ row.shopId }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="正式版本" prop="onlieVersion"></el-table-column>
            <el-table-column label="发布时间" prop="releaseTime"></el-table-column>
            <el-table-column label="提审版本" prop="verifyVersion"></el-table-column>
            <el-table-column label="审核状态" prop="verifyStatus">
                <template v-slot="{ row }">
                    <span :class="['status-cil', 'auth-' + row.verifyStatus]" v-if="row.verifyStatus !== 3">
                        {{ transformStream(row.verifyStatus, 'VERSION_MP_LIST') }}
                    </span>
                    <el-tooltip v-else class="box-item" effect="dark" :content="row.failReason" placement="top">
                        <span :class="['status-cil', 'auth-' + row.verifyStatus]">
                            {{ transformStream(row.verifyStatus, 'VERSION_MP_LIST') }}
                        </span>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="100">
                <template v-slot="{ row }">
                    <el-tooltip
                        v-if="row.failReason"
                        class="box-item"
                        effect="dark"
                        :content="row.failReason"
                        placement="top">
                        <span>
                            <el-button size="small" disabled @click="pushHandler(row)">发布</el-button>
                        </span>
                    </el-tooltip>
                    <el-popconfirm
                        v-else
                        confirm-button-text="确认"
                        cancel-button-text="取消"
                        width="200px"
                        :title="`你确定要给该小程序发布最新版本${newMiniapp.version}吗？`"
                        @confirm="pushHandler(row)">
                        <template #reference>
                            <el-button size="small">发布</el-button>
                        </template>
                    </el-popconfirm>

                    <el-button class="table-btn" size="small" @click="historyHandler(row)"> 更新记录 </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination zw-pagination">
            <Pagination
                :total="totalCount"
                :page-size="form.pageSize"
                :current-page="form.pageNum"
                @size-change="changeSizeHandler"
                @pageChange="changePageHandler" />
        </div>
        <el-dialog v-model="historyShow" width="40%">
            <template #header>
                <span>更新记录</span>
            </template>
            <template #default>
                <el-table :data="historyTableList" :border="true" stripe>
                    <el-table-column label="版本号" prop="version"></el-table-column>
                    <el-table-column label="发布时间" prop="releaseTime"></el-table-column>
                </el-table>
                <div class="pagination zw-pagination">
                    <el-pagination
                        layout="total, prev, pager, next"
                        :total="historyTotalCount"
                        :page-size="historyForm.pageSize"
                        :current-page="historyForm.pageNum"
                        @current-change="changeHistoryPageHandler">
                    </el-pagination>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, inject } from 'vue';
import constants from '@/commons/constants';
import Pagination from '@/components/Pagination.vue';
import request from '@/request/index';
import { packSelectObjUtil, format } from '@/commons/utils';
import { ElMessage } from 'element-plus';

const defaultDateRange = [new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)];
const confirm = inject('confirm');
let totalCount = ref(0);
const form = reactive({
    appid: '',
    onlineVersion: '',
    status: '',
    date: [],
    releaseStart: '',
    releaseEnd: '',
    pageNum: 1,
    pageSize: 10
});
let tableList = reactive([]);
const formRef = ref(null);
const statusList = reactive(packSelectObjUtil(constants.VERSION_MP_LIST));
const historyShow = ref(false);
let multipleSelection = ref([]);
let newMiniapp = reactive({
    version: '',
    createTime: ''
});
let historyTotalCount = ref(0);
const historyForm = reactive({
    id: '',
    pageNum: 1,
    pageSize: 10
});
let historyTableList = reactive([]);

/**
 * 时间范围
 */
let queryDate = computed({
    get: function () {
        return [form.releaseStart, form.releaseEnd].map(v => v.substring(0, 10) + ' ' + v.substring(10, v.length));
    },
    set: function (val) {
        if (val.length === 2) {
            form.releaseStart = format(val[0], 'YYYY-MM-DD HH:mm:ss');
            form.releaseEnd = format(val[1], 'YYYY-MM-DD HH:mm:ss');
        } else {
            form.releaseStart = '';
            form.releaseEnd = '';
        }
    }
});

/**
 * 分页查询
 */
const queryHandler = async () => {
    let result = {};
    Object.assign(result, form);
    if (result.date?.length) {
        result.releaseStart = result.date[0];
        result.releaseEnd = result.date[1];
    } else {
        result.releaseStart = '';
        result.releaseEnd = '';
    }
    delete result.date;
    const res = await request('miniappReleaseListServ', result);
    const { list } = res.data;
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.totalCount;
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.pageNum = 1;
    queryHandler();
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    queryDate.value = [];
    queryHandler();
};

/**
 * 分页
 * @param {*} pageNum
 */
const changePageHandler = pageNum => {
    form.pageNum = pageNum;
    queryHandler();
};

/**
 * 每页记录数修改
 * @param {*} pageSize
 */
const changeSizeHandler = pageSize => {
    form.pageNum = 1;
    form.pageSize = pageSize;
    queryHandler();
};

/**
 * 发布
 * @param {*} row
 */
const pushHandler = async row => {
    await request('miniappReleaseBatchPushServ', { id: [row.shopId] });
    ElMessage.success('操作成功');
    queryHandler();
};

/**
 * 批量选中状态
 * @param {*} val
 */
const handleSelectionChange = val => {
    multipleSelection.value = val;
};

/**
 * 获取选中的记录ID
 */
const getBatchIds = () => {
    const ids = [];
    multipleSelection.value.map(v => {
        ids.push(v.shopId);
    });
    return ids;
};

/**
 * 批量发布
 * @param {*} row
 */
const batchPushHandler = async row => {
    const ids = getBatchIds();
    if (
        await confirm(
            `<b>确定要给所选${ids.length}个小程序发布最新版本${newMiniapp.version}吗？</b>
            <p>发布后所选小程序提交微信审核版本${newMiniapp.version}，发布后不可撤销。</p>`,
            'warning',
            ``,
            true
        )
    ) {
        await request('miniappReleaseBatchPushServ', { id: getBatchIds() });
        ElMessage.success('操作成功');
        multipleSelection.value.length = 0;
        queryHandler();
    }
};

/**
 * 批量回滚
 * @param {*} row
 */
const batchRevertHandler = async row => {
    const ids = getBatchIds();
    if (
        await confirm(
            `<b>确定要给所选${ids.length}个小程序进行回滚吗？</b>
            <p>回滚后所选小程序自动回滚至上次发布的版本。</p>`,
            'warning',
            '',
            true
        )
    ) {
        await request('miniappRevertBatchServ', { id: getBatchIds() });
        ElMessage.success('操作成功');
        multipleSelection.value.length = 0;
        queryHandler();
    }
};

/**
 * 查询最新版的小程序
 */
const queryMpListHandler = async () => {
    const res = await request('miniappListServ', form);
    const { list } = res.data;
    if (list.length > 0) {
        Object.assign(newMiniapp, list[0]);
    }
};

/**
 * 更新记录：查询
 */
const queryHistoryHandler = async () => {
    const res = await request('miniappreleaseRecordServ', historyForm);
    const { list } = res.data;
    historyTableList.length = 0;
    historyTableList.push(...list);
    historyTotalCount.value = res.data.totalCount;
};

/**
 * 更新记录: 弹框显示
 * @param {*} row
 */
const historyHandler = row => {
    historyForm.id = row.shopId;
    historyForm.pageNum = 1;
    queryHistoryHandler();
    historyShow.value = true;
};

/**
 * 更新记录：分页
 * @param {*} pageNum
 */
const changeHistoryPageHandler = pageNum => {
    historyForm.pageNum = pageNum;
    queryHistoryHandler();
};

onMounted(async () => {
    queryMpListHandler();
    searchHandler();
});
</script>
<style lang="scss" src="./style.scss" scoped></style>
